package com.ocm.burnningstar.View;

import android.app.Fragment;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.blankj.utilcode.util.ScreenUtils;
import com.ocm.burnningstar.Adapter.CourseAdapter;
import com.ocm.burnningstar.Interface;
import com.ocm.burnningstar.MainActivity;
import com.ocm.burnningstar.Model.SportUser;
import com.ocm.burnningstar.R;
import com.ocm.burnningstar.Utils.Helper;
import com.shape.sdk.Course;
import com.shape.sdk.FitnessData;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@ContentView(R.layout.activity_course)
public class CourseFragment extends Fragment {

    String T="CourseFragment";
    @ViewInject(R.id.list_course)
    RecyclerView list_course;
    @ViewInject(R.id.backvideo)
    VideoView videoView1;
    @ViewInject(R.id.list_parent)
    LinearLayout listparent;
    int COLUMN = 2;
    long playTime = 60*1000;

    boolean isReady = false;
    MainActivity mainActivity;
    CourseAdapter course;
    MediaPlayer mediaPlayer = null;
    boolean isPlaying =false;
    String oldAudio="";
    Course mCourse;
    int audioIndex =0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(T,"onCreate");
        super.onCreate(savedInstanceState);
        mainActivity = (MainActivity)getActivity();
        mainActivity.SetCourseListener(courseLs);
    }
    Interface.CourseListener courseLs= new Interface.CourseListener() {
        @Override
        public void run(List<FitnessData> data) {
            updateData(data);
        }

        @Override
        public void over() {
            isPlaying = false;
            Log.i("onDestroyView","");
            if(countDownTimer!=null)countDownTimer.cancel();
            if(mediaPlayer!=null){
                if (mediaPlayer != null) {//在播放状态才可以停止播放
                    mediaPlayer.release();
                }
            }
        }
    };

    CountDownTimer countDownTimer = null;
    long ChangeTime = 0;


    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.i(T,"onCreateView");
        return x.view().inject(this, inflater, container);
    }
    @Override
    public void onViewCreated(View v, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        Log.i(T,"onViewCreated");
        int screenWidth = ScreenUtils.getScreenWidth();
        int screenHeight = (int)(ScreenUtils.getScreenHeight());
        FrameLayout.LayoutParams linearLayoutParams = (FrameLayout.LayoutParams) listparent.getLayoutParams();
        int marginleft =(int) (screenWidth*0.11);
        int margintop =(int)( screenHeight*0.15);

        linearLayoutParams.width =(int)(screenWidth*0.78);
        linearLayoutParams.height =(int)(screenHeight*0.70);

        linearLayoutParams.setMargins(marginleft,margintop,0,0);
        listparent.setLayoutParams(linearLayoutParams);
        InitAudio();
        if(mCourse!=null&&mCourse.getPlayList().size()>0){
            Course.VideoUnit vu = mCourse.getPlayList().get(0);
            ChangeTime = vu.getVideDuration();
            playTime = mCourse.getDuration()*1000;
            Log.i("Course","ChangeTime:"+ChangeTime+",playTime:"+playTime);
            startMedia(vu.getAudio());
        }
        init();
        isReady = true;
    }
    public void setCourseData(Course coursse){
        mCourse = coursse;
    }
    void InitAudio() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setLooping(true);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                InitAudio();
                return false;
            }
        });
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                Log.i(T,"音频准备就绪 开始播放");
                mediaPlayer.setVolume(1f, 1f);
                mediaPlayer.start();
            }
        });
        try {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void startMedia(String audio){
        if(checkPath(audio)){
            try {
                if(!oldAudio.equals(audio)){
                    if (oldAudio.length()>0)mediaPlayer.reset();
                    mediaPlayer.setDataSource(audio);
                    mediaPlayer.prepareAsync();
                    oldAudio = audio;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    boolean checkPath(String path){
        if(path==null)return false;
        int index = path.lastIndexOf('/');
        String pathTmp = path.substring(0,index);
        File file=new File(pathTmp);
        if(!file.exists())
            file.mkdir();
        try{
            if(new File(path).exists())return true;
        }catch (Exception e){
            return false;
        }
        return false;
    }
    int[] resources =new int[]{R.drawable.shape_course1,R.drawable.shape_course2,R.drawable.shape_course3,R.drawable.shape_course4};;
    void init(){
        //0-4 依次降低
        List<SportUser> users = new ArrayList<>();
//        for(int i =0;i<4;++i){
//            SportUser user = new SportUser();
////            Bitmap bm =((BitmapDrawable) getResources().getDrawable(R.drawable.test1)).getBitmap();
////            user.setHeader(bm);
//            user.setHeaderStr();
//            user.setHeartRate(123);
//            user.setStrength(11);
//            user.setCalorie(123);
//            user.setName("asd");
//            user.setResource(resources[i]);
//            users.add(user);
//        }
        course = new CourseAdapter(getActivity(),users);
        list_course.setAdapter(course);

//        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), COLUMN, GridLayoutManager.VERTICAL, false);
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), COLUMN);
        list_course.setLayoutManager(layoutManager);
        list_course.addItemDecoration(new GridSpacingItemDecoration(COLUMN,30, true));
        list_course.setHasFixedSize(false);


        countDownTimer = new CountDownTimer(playTime,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if(ChangeTime==0){
                    Log.i("Course","changeAudio");
                    audioIndex++;
                    List<Course.VideoUnit> vus = mCourse.getPlayList();
                    if(vus!=null&&audioIndex<vus.size()){
                        ChangeTime = vus.get(audioIndex).getVideDuration();
                        startMedia(vus.get(audioIndex).getAudio());
                    }
                }else{
                    ChangeTime--;
                }
            }

            @Override
            public void onFinish() {
                nextListener.ClassOver();
            }
        };
        countDownTimer.start();
    }
    public class MyPrepatedListener implements MediaPlayer.OnPreparedListener {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            videoView1.start();
        }
    }

    public class MyCompetionListener implements MediaPlayer.OnCompletionListener {
        final VideoView videoView;
        MyCompetionListener(VideoView videoView) {
            this.videoView = videoView;
        }

        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            videoView.start();
        }
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        Log.d(T,"onConfigurationChanged");
        if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            double mwidth = layoutParams.height*0.5625;
            layoutParams.width = layoutParams.width>mwidth?(int)mwidth:layoutParams.width;
            videoView1.setLayoutParams(layoutParams);
        }
        super.onConfigurationChanged(newConfig);
    }
    void updateData(List<FitnessData> data){
        if(!isReady||!isAdded())return;
        List<SportUser> users = new ArrayList<>();
        if(data!=null){
        int len = data.size()>=4?4:data.size();
            if(len>0){
//            videoView1.stopPlayback();
                videoView1.setVisibility(View.INVISIBLE);
            }else{
                videoView1.setVisibility(View.VISIBLE);
            }
        for(int i =0;i<len;i++){
            SportUser user = new SportUser();
            FitnessData fd = data.get(i);
            user.setHeaderStr(fd.getUser().getAvatar());
            user.setHeartRate(fd.getHeartRate());
            user.setStrength(fd.getPercent());
            user.setCalorie(fd.getCalories());
            user.setName(fd.getUser().getName());
            user.setResource(resources[Helper.percent2State(fd.getPercent())]);
            users.add(user);
        }}
        course = new CourseAdapter(getActivity(),users);
        list_course.setAdapter(course);
    }
    NextListener nextListener;

    public void SetNextListener(NextListener next){
        nextListener = next;
    }

    public interface NextListener{
        void ClassOver();
        void GoNext();
    }
}
